package com.yyg.boot.web;

import com.yyg.boot.domain.OrderForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

import javax.validation.Valid;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description Description
 * @Author 一一哥Sun
 * @Date Created in 2020/3/23
 */
@Slf4j
@RestController
public class BindController {

    /**
     * @InitBinder标注的方法,只针对当前Controller有效! 如果没有该方法, 则会产生400状态码!
     * MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date!
     */
    @InitBinder
    public void InitBinder(WebDataBinder binder) {
        //前端传入的时间格式必须是"yyyy-MM-dd"效果!
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor dateEditor = new CustomDateEditor(df, true);
        binder.registerCustomEditor(Date.class, dateEditor);
    }

    @GetMapping(value = "/bind")
    public Map<String, Object> getFormatData(Date date) throws ParseException {
        log.warn("date={}", date);
        Map<String, Object> map = new HashMap<>();
        map.put("name", "一一哥");
        map.put("age", 30);
        map.put("date", date);
        return map;
    }

    @PostMapping(value = "/order")
    public String order(@Valid @RequestBody OrderForm form,BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return bindingResult.getFieldError().getDefaultMessage();
        }

        log.warn("order={}",form.toString());

        return "success";
    }

}
